Eleron
0
Q:

create object python

class Person:
  def __init__(self, _name, _age):
    self.name = _name
    self.age = _age
   
  def sayHi(self):
    print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
    
p1 = Person('Bob', 25)
p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!
17
class Mammal:
    def __init__(self, name):
        self.name = name

    def walk(self):
        print(self.name + " is going for a walk")


class Dog(Mammal):
    def bark(self):
        print("bark!")


class Cat(Mammal):
    def meow(self):
        print("meow!")


dog1 = Dog("Spot")
dog1.walk()
dog1.bark()
cat1 = Cat("Juniper")
cat1.walk()
cat1.meow()
12

  class MyClass:
  	x = 5
    def __init__(self, name):
      self.name=name
    def sayname(self):
      print(self.name)
    def getnum(self):
      return x
  y=MyClass("Henry")
  y.sayname()
  print(y.getnum()*5)
 
  
9
class ClassName(object): #"(object)" isn't mandatory unless this class inherit from another
  	def __init__(self, var1=0, var2):
    
    	#the name of the construct must be "__init__" or it won't work
    	#the arguments "self" is mandatory but you can add more if you want 
    	self.age = var1
    	self.name = var2
    
    	#the construct will be execute when you declare an instance of this class
    
  	def otherFunction(self):
    	
        #the other one work like any basic fonction but in every methods,
    	#the first argument (here "self") return to the class in which you are
 	
4
class ClassName:
    self.attribute_1 = variable_1 #Set attributes for all object instances
    self.attrubute_2 = variable_2
    
    def __init__(self, attribute_3, attribute_4): #Set attributes at object creation
        self.attribute_3 = attribute_3            
        self.attribute_4 = attribute_4

    def method(self): #All methods should include self
		print("This is a method example.") #Define methods just like functions 


object = Object(4, "string") #Set attribute_3 and attribute_4
object.method() #Methods are called like this.
0
class person:
    name = "jake"
    age = 13
x = vars(person)
print(x)
0

New to Communities?

Join the community