Andrew
0
Q:

how to define a class in 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 uneclasse():
  def __init__(self):
    pass
  def something(self):
    pass
xx = uneclasse()
xx.something()
1
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 person:
    name = "jake"
    age = 13
x = vars(person)
print(x)
0
class a_class:
  #This initalizes the object, and is executed when you define
  #a new object in the class
  def __init__(self, input1):
    self.__input1 = input1
    
  #This is a function of the object that can be called
  def return_input(self):
    return self.__input1
  
a_class_object = a_class("input string")
print(a_class_object.return_input())
-1

New to Communities?

Join the community