Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python class name

instance.__class__.__name__
Comment

python class

class Person:
    # class static variable
    person_type = "Human"

    # class constructor
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    # initialized class method
    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

    # initialized class method
    def introduce(self):
        return f"Hi. I'm {self.first_name} {self.last_name}. I'm {self.age} years old."

    # class static method
    @staticmethod
    def class_name(self):
        return 'Person'

    # class method
    @classmethod
    def create_anonymous(cls):
        return Person('John', 'Doe', 25)

    # dunder method - return class as a string when typecast to a string
    def __str__(self):
        return f"str firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"

    # dunder method - return class a string then typecast to representative
    def __repr__(self):
        return f"repr firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"

    # dunder method - return sum of ages when using the + operator on two Person classes
    def __add__(self, other):
        return self.age + other.age


# create a person class
bob = Person(first_name="John", last_name="Doe", age=41)

# print static method
print(Person.class_name(Person))

# print new class person
print(Person.create_anonymous().get_full_name())

# print class static method
print(Person.person_type)

# print string representation of class
print(bob)

# print representation of class
print(repr(bob))

# add Person classes ages using dunder method
print(bob + bob)
Comment

python class

class Person:#set name of class to call it 
  def __init__(self, name, age):#func set ver
    self.name = name#set name
    self.age = age#set age
   

    def myfunc(self):#func inside of class 
      print("Hello my name is " + self.name)# code that the func dose

p1 = Person("barry", 50)# setting a ver fo rthe class 
p1.myfunc() #call the func and whitch ver you want it to be with 
Comment

python class

# Standard way of writing a simple class
class Person1:
# Type hinting not required
    def __init__(self, name: str, age: int, num_children=0):
        self.name = name
        self.age = age
        self.num_children = num_children

    def __repr__(self):
        return f'My name is {self.name}, I am {self.age} years old, and I have {self.num_children} children'

      
from dataclasses import dataclass


# A class using data classes. Dataclasses are simpler but can't support operations during initialization
@dataclass()
class Person2:
    """ This class handles the values related to a person. """
    name: str  # Indicating types is required
    age: int
    num_children = 0  # Default values don't require an indication of a type

    def __repr__(self):
        return f'My name is {self.name}, I am {self.age} years old, and I have {self.num_children} children'

# Both classes (Person1 and Person2) achieve the same thing but require different code to do it

person1 = Person1('Joe', 28, 2)
print(person1)
# Result: My name is Joe, I am 28 years old, and I have 2 children

person2 = Person2('Emma', 19)
print(person2)
# Result: My name is Emma, I am 19 years old, and I have 0 children
Comment

python class

class Animal(object): # Doesn't need params but put it there anyways.
    def __init__(self, species, price):
        self.species = species # Sets species name
        self.price = price # Sets price of it
    
    def overview(self): # A function that uses the params of the __init__ function
        print(f"This species is called a {self.species} and the price for it is {self.price}")

class Fish(Animal): # Inherits from Animal
    pass # Don't need to add anything because it's inherited everything from Animal
 
salmon = Fish("Salmon", "$20") # Make a object from class Fish
salmon.overview() # Run a function with it
dog = Animal("Golden retriever", "$400") # Make a object from class Animal
dog.overview() # Run a function with it
Comment

python class

class Human():
    def __init__(self, _name, _age):
        self.name = _name
        self.age = _age

    def walk(self):
        print("walking...")

Person = Human('John', 32)
Person.walk()
Comment

python class


class Dog(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak(self):
        print("Hi I'm ", self.name, 'and I am', self.age, 'Years Old')

JUB0T = Dog('JUB0T', 55)
Friend = Dog('Doge', 10)
JUB0T.speak()
Friend.speak()
Comment

python class

class Dog:

    def bark(self):
        print("Woof!")

    def roll(self):
        print("*rolling*")

    def greet(self):
        print("Greetings, master")

    def speak(self):
        print("I cannot!")

# Creating the Dog class instance and saving it to the variable <clyde>
clyde = Dog()
clyde.bark()   # --> Woof!
clyde.roll()   # --> *rolling*
clyde.greet()  # --> Greetings, master
clyde.speak()  # --> I cannot!

# Creating another Dog instance
jenkins = Dog()
jenkins.bark()  # --> Woof!
jenkins.roll()  # --> *rolling*
# .. And other methods
# .. Infinite objects can be created this way, all implementing the same methods defined in our class
Comment

python class

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
Comment

python class

class Car():
    def __init__(self, _name, _year):
        self.name = _name
        self.age = _age

    def start(self):
        print("starting...")
        
    def drive(self):
    	print("Vroom Vroom!")

myCar = Car('Audi', 2019)
myCar.start()
myCar.drive()
Comment

PREVIOUS NEXT
Code Example
Python :: make lists for each 2 items in a list 
Python :: py how to deactivate venv 
Python :: taking string input from user in python with try except 
Python :: python smtp email 
Python :: plot rows of dataframe pandas 
Python :: pyqt loading screen 
Python :: how to set up a postgress database for your django projecrt 
Python :: python run system command 
Python :: instagram login with selenium py 
Python :: enumerate python 
Python :: how to make images in python 
Python :: rotate image by specific angle opencv 
Python :: python catch multiple exceptions 
Python :: python day of the week 
Python :: python one line if else 
Python :: bar labeling in matplotlib 
Python :: python check folder exists 
Python :: django rest documentation 
Python :: Get last “column” after .str.split() operation on column in pandas DataFrame 
Python :: how to convert string date to timestamp in python 
Python :: python average 
Python :: falsy values in python 
Python :: python kill process by name 
Python :: convert string to utf8 python 
Python :: find average of list python 
Python :: python [remote rejected] master - master (pre-receive hook declined) 
Python :: pandas filter every column not null 
Python :: python open excel application 
Python :: python execute shell command and get output 
Python :: pandas apply function to every row 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =