Friday, August 14, 2020

Classes in python

 basic class creation with instance and class variables.And about methods and self argument.

You can use a different keyword instead of self also.

class Dog:
    dogInfo = "This is class variable"

    def bark1(self):
        print("sample function,all methods should have self")

    def bark2(self,str):
        print("BARK!" + str)


mydog = Dog #new oject created.
mydog.bark1()
mydog.bark2("asdasd")#second argument, as first is always current object reference.
mydog.name = "FSDFd" #variable name is not declared in the class but created on go.
mydog.age = 16

print(mydog.name)
print(mydog.age)

Dog.dogInfo = "new value" #Class variable and no need to create object access it.,common for all objects of class 
print(Dog.dogInfo)

With constructor to a class

When you create a new constructor, the default constructor will be not valid, we need to create ourselves.


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


    def bark(self,str):
        print("BARK!" + str)


mydog = Dog("Fido",13,"Brown") #new oject created with specified values.
print(mydog.age)

So, mydog= Dog() #will give an error as parameters missing.
The below code uses default arguments, so you can call without arguments.


class Dog:
    def __init__(self,name="",age=0,furcolor=""):
        self.name = name
        self.age=age
        self.furcolor=furcolor


    def bark(self,str):
        print("BARK!" + str)


mydog = Dog() #new oject created with default argument values.
print(mydog.age)

No comments:

Post a Comment