Answers for "create a class python"

22

how to make 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!
Posted by: Guest on November-17-2019
16

declare class python

# To create a simple class:
class Shape:
  	def __init__():
      	print("A new shape has been created!")
      	pass
    
    def get_area(self):
		pass

# To create a class that uses inheritance and polymorphism
# from another class:
class Rectangle(Shape):
  
	def __init__(self, height, width): # The constructor
    	super.__init__()
        self.height = height
    	self.width = width

	def get_area(self):
      	return self.height * self.width
Posted by: Guest on March-08-2020
4

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()
Posted by: Guest on November-20-2020
2

classes in python

class Foo:
  def __init__(self):
    self.definition = Foo!
  def hi():
    # Some other code here :)
    
# Classes require an __init__ if you want to assign attributes. (self) defines what describes the attribs.
Posted by: Guest on January-21-2021
1

python classes

class Student:
  def __init__(self, id, name, age):
    self.name = name
    self.id = id
    self.age = age
  
  def greet(self):
    print(f"Hello there.nMy name is {self.name}")
    
  def get_age(self):
    print(f"I am {self.age}")
    
  def __add__(self, other)
  	return Student(
      self.name+" "+other.name,
      self.id + " "+ other.id,
      str(self.age) +" "+str(other.age))
    
p1 = Student(1, "Jay", 19)
p2 = Student(2, "Jean", 22)
p3 = Student(3, "Shanna", 32)
p4 = Student(4, "Kayla", 23)


result = p1+p3
Posted by: Guest on February-16-2021
0

why should i use classes in python

"Why should I use classes in python?"

Classes are essential in OOP.
A good reason to use classes is to make your code structured and organised. 
Furthermore it is easy to import functions when they are part of a class since you can just import the class.
Classes provide methods that are useful such as the __repr__ method which allows you to represent an object by a string.
Classes allow for access control (encapsulation) by using the underscore character.
Posted by: Guest on July-19-2021

Python Answers by Framework

Browse Popular Code Answers by Language